<template>
  <div class="file-input">
    <el-upload
        action="http://upload.qiniup.com"
        :auto-upload="true"
        :list-type="listType"
        :limit="limit"
        :on-preview="onPreview"
        :before-upload="beforeUpload"
        :file-list="fileList"
        :on-success="(response, file, files)=>onSuccess(file)"
        :data="qData"
        :on-remove="(file, fileList)=>onRemove(file)">
      <i v-if="type==0" class="el-icon-plus"></i>
      <el-button v-else size="small" type="primary">点击上传</el-button>
    </el-upload>

    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import {domain,getToken} from "@/api/qiniu";
import {listToStrs, strsToList} from "@/utils/imgUtil";

export default {
  created() {
    getToken().then(res => {
      this.qData.token = res.data
    })
  },
  computed:{
    fileList(){
      return  strsToList(this.value, domain)
    },
    listType(){
      if(this.type ==0 ){
        return  'picture-card'
      }else {
        return  'text'
      }
    }
  },
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: null,
      qData: {
        token: '',
        key: ''
      }
    }
  },
  methods: {
    beforeUpload(file) {
      this.qData.key = new Date().valueOf() + file.name
    },
    onSuccess(file){
      this.fileList.push({name: file.response.key, url: domain + file.response.key})
      this.$emit("input",listToStrs(this.fileList))
      console.log(listToStrs(this.fileList))
    },
    onRemove(file){
      for (let fn of this.fileList) {
        if (fn.name === file.name) {
          this.fileList.splice(this.fileList.indexOf(fn), 1)
        }
      }
      this.$emit("input",listToStrs(this.fileList))
    },
    onPreview(file) {
      if (this.type == 0) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      }
    }
  },
  props: {
    limit:Number,
    value:String,
    type: {
      type: Number,
      default: 0
    }
  }
}
</script>

<style scoped>

</style>